/*关于个人中心信息的存储*/

import { defineStore } from "pinia";
import { GetUserInfo, UpdateUserInfo } from "../utils/api";
import axios from '../utils/axios'

export const useUserInfoStore = defineStore("userInfo", {
    state: () => ({
        userInfo: {
            avatar: "",
            loginName: "",
            userName: "",
            realName: "",
            email: "",
            phoneNumber: "",
            qqNumber: "",
            remark: "",
            id: ""
        }
    }),
    actions: {
        setUserInfo(data) {
            this.userInfo = { ...data };
        },
        clearUserInfo() {
            this.userInfo = {
                id: '',
                userName: '',
                avatar: '',
                loginName: '',
                phoneNumber: '',
                email: '',
                qqNumber: '',
                realName: '',
                remark: '',
            };
        },
        async GetUserInfo() {
            try {
                const result = await GetUserInfo();
                if (result.statusCode == 200 && result.success == true) {
                    this.userInfo = result.response;
                } else {
                    console.log(result.message || "获取用户信息失败");
                }
            }
            catch {
                ElMessage.error(error.message)
            }
        },
        async UpdateUserInfo(data) {
            try {
                if (await UpdateUserInfo(data)) {
                    this.userInfo = { ...this.userInfo, ...data }; // 更新 Store
                    return true; // 返回成功状态
                } else {
                    return false
                }
            } catch (error) {
                ElMessage.error(error.message)
                return false
            }
        },
    },
    getters: {
        // 获取欢迎信息
        welcome(state) {
            return state.userInfo.userName ? `欢迎你，${state.userInfo.userName}` : '未登录';
        },
    },
    persist: {
        enable: true,
        strategise: [
            {
                storage: localStorage, // 持久化到本地存储
                paths: ['userInfo'] // 指定需要持久化的字段
            }
        ]
    }
})
